package com.sys.midware.MQ.rocketMQ.factory;

import com.sys.midware.MQ.rocketMQ.config.ConfigRocketUtil;
import com.sys.midware.MQ.rocketMQ.logic.IProducer;
import com.sys.midware.MQ.rocketMQ.logic.impl.ProducerImpl;
import com.sys.midware.assist.utils.Assert;
import com.sys.midware.assist.utils.string.StringUtil;
import com.sys.midware.logger.Logger;
import com.sys.midware.logger.LoggerFactory;

/**
 * 获取默认的消息生产实力 <b>ClassName：</b> ProducerFactory <br/>
 * <b>Description：</b> TODO <br/>
 * <b>@author：</b> mobing <br/>
 * <b>@date：</b> 2015年10月19日 下午2:54:26 <br/>
 * <b>@version: </b> <br/>
 */
public class ProducerFactory {
    private static final Logger logger = LoggerFactory.getLogger(ProducerFactory.class);

    /**
     * IProducer 接口定义
     */
    private static IProducer producer = null;

    /**
     * 获取默认消息生产实例
     * @return IProducer
     */
    public static IProducer getProducerInstace() {
        return getProducerInstace(null);
    }

    /**
     * 获取消息生产实例
     * @param producerGroup
     *            消息发送的组名
     * @return IProducer
     */
    public static IProducer getProducerInstace(String producerGroup) {
      
        return getProducerInstace(null,producerGroup);
    }
    
    /**
     * 获取消息生产实例
     * @param producerGroup
     *            消息发送的组名
     * @return IProducer
     */
    public static IProducer getProducerInstace(String instance,String producerGroup) {
        if (null != producer) {
            return producer;
        }
        //如果引用未传，则走配置文件
        if (StringUtil.isEmpty(producerGroup)) {
            producerGroup = ConfigRocketUtil.getMQGroupProducer();
        }
        synchronized (ProducerFactory.class) {
            if (null == producer) {
                String nameServer = ConfigRocketUtil.getRocketNameServer();
                if(StringUtil.isEmpty(nameServer)){
                    Assert.notNull(nameServer, "RocketNameServer can not null!");
                }
                if(instance ==null){
                    instance =producerGroup;
                }
                producer = new ProducerImpl(nameServer,instance,producerGroup);
                producer.start();
                Runtime.getRuntime().addShutdownHook(new CleanHook());
            }
        }
        return producer;
    }
    
    static void clean() {
        try {
            producer.shutdown();
        } catch (Exception e) {
            logger.error("clean producer error!", e);
        }
    }

    static class CleanHook extends Thread {
        public void run() {
            clean();
        }
    }
}
